var maintenanceTitle = ['设备名称', '设备类型', '设备编号', '状态', '维保周期', '上次维保日期', '应维保日期', '下次维保日期'];
var maintenanceLabel = ['name', 'deviceType', 'sn', 'status', 'cycle', 'lastMaintenance', 'maintenanceDate', 'nextMaintenance'];
var toPage;
var prdEquMaintenanceCookieNum = 1;
var pageSize = 5;
$(function () {
    loadDeviceType($('#deviceType-select'));
    chart_pie.setOption(option_pie);
    chart_pie2.setOption(option_pie);
    chart_pie2.setOption({
        color: ['#F8DD83', '#0096FF', '#5DDF91', '#FF7931', '#718BF3',],
        series: [{
            data: [
                {value: 0, name: '定保'},
                {value: 0, name: '一级保养'},
                {value: 0, name: '二级保养'},
                {value: 0, name: '预防性维修'},
                {value: 0, name: '故障维修'}
            ]
        }]
    });
    if ($.cookie("prdEquMaintenanceCookieNum")) {
        prdEquMaintenanceCookieNum = $.cookie("prdEquMaintenanceCookieNum");
        loadMaintenanceData(prdEquMaintenanceCookieNum);
    } else {
        loadMaintenanceData();
    }
    loadMaintenanceList();
    userInfo($('#userInfo'));
})

var title = ['#', '设备名称', '设备类型', '设备编号', '维保种类', '计划时间', '完成时间', '实施用时', '维保内容', '更换材料清单', '实施人', '检查验证人', '照片'];
var label = ['order', 'name', 'deviceType', 'sn', 'species', 'planningTime', 'maintenanceTime', 'timeCost', 'content', 'materialList', 'implementer', 'checkVerifier', 'image'];

function loadMaintenanceData() {
    loadMaintenanceListTwo()
    loadMaintenanceCount();
}

function loadMaintenanceCount() {
    getJson("/maintenance/countMaintenanceInfoByParam", {
            dateTime: $('#searchTime').val(),
            type: 1,
            name: $('#name').val(),
            deviceType: $('#deviceType-select').val()
        }, 'GET', function (data) {
            var payload = data['payload']['data'];
            /*定保*/
            var dingBao = 0;
            /*故障维修*/
            var malfunction = 0;
            /*预防*/
            var prevention = 0;
            /*二级*/
            var LevelT = 0;
            /*一级*/
            var LevelO = 0;
            payload.map(function (item) {
                switch (item['species']) {
                    case 1:
                        dingBao += item['count'];
                        break;
                    case 2:
                        LevelO += item['count'];
                        break;
                    case 3:
                        LevelT += item['count'];
                        break;
                    case 4:
                        prevention += item['count'];
                        break;
                    case 5:
                        malfunction += item['count'];
                        break;
                }
            });
            chart_pie2.setOption({
                color: ['#F8DD83', '#0096FF', '#5DDF91', '#FF7931', '#718BF3',],
                series: [{
                    data: [
                        {value: dingBao, name: '定保次数'},
                        {value: LevelO, name: '一级保养'},
                        {value: LevelT, name: '二级保养'},
                        {value: prevention, name: '预防性维修'},
                        {value: malfunction, name: '故障维修'}
                    ]
                }]
            });
            $('#record_count').text(dingBao + LevelO + LevelT + prevention + malfunction);
        }
    )
}

function loadMaintenanceListTwo(_pageIndex) {
    showLoading(LOADING);
    var pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    getJson("/maintenance/getMaintenanceInfoByParam", {
        dateTime: $('#searchTime').val(),
        type: 1,
        name: $('#name').val(),
        deviceType: $('#deviceType-select').val(),
        pageIndex: pageIndex,
        pageSize: pageSize
    }, 'GET', function (data) {
        var payload = data['payload'];
        if (pageIndex > payload['pages']) {
            pageIndex = 1;
            $.cookie("prdEquMaintenanceCookieNum", pageIndex, {path: '/'});
        }
        var order = 1 + pageSize * (pageIndex - 1);
        payload.data.map(function (item) {
            item['order'] = order++;
        });

        buildTable($("#materialList"), title, label, payload['data'], function (td, label, item) {
            switch (label) {
                case "content":
                    $(td).empty();
                    var div = createElement("div", $(td), item['content'], null);
                    $(div).addClass('text-truncate').addClass('more-tooltip');
                    $(div).attr('data-toggle', 'tooltip');
                    $(div).attr('title', item['content']);
                    break;
                case "materialList":
                    $(td).empty();
                    var div2 = createElement("div", $(td), item['materialList'], null);
                    $(div2).addClass('text-truncate').addClass('more-tooltip');
                    $(div2).attr('data-toggle', 'tooltip');
                    $(div2).attr('title', item['materialList']);
                    break;
                case "planningTime":
                    $(td).empty();
                    if (item['species'] == 1) {
                        var lastMaintenance = parseInt(item['lastMaintenanceTime']);
                        var cycle = parseInt(item['maintenanceCycle']);
                        /*下次维保时间*/
                        var nextMaintenance = lastMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
                        $(td).text(getDate(nextMaintenance).date());
                    }
                    break;
                case "species":
                    $(td).empty();
                    var tem = '';
                    switch (item['species']) {
                        case 1:
                            tem = '定保';
                            break;
                        case 2:
                            tem = '一级保养';
                            break;
                        case 3:
                            tem = '二级保养';
                            break;
                        case 4:
                            tem = '预防性维修';
                            break;
                        case 5:
                            tem = '故障维修';
                            break;
                    }
                    $(td).text(tem);
                    break;
                case "image":
                    $(td).empty();
                    if (!isNull(item['image'])) {
                        var img = createElement("img", td);
                        $(img).addClass('img-preview');
                        $(img).attr('src', fileUrl + concatMinImgUrl(item['image']));
                        $(img).attr('data-origin', fileUrl + item['image']);
                    }
                    break;
                case 'maintenanceTime':
                    $(td).empty();
                    $(td).text(getDate(item['maintenanceTime']).datetime());
                    break;
                case 'opera':
                    var edit = createElement('a', td);
                    $(edit).addClass('circle-btn');
                    $(edit).attr('href', '##');
                    $(edit).click(function () {
                        editInfo(item['id']);
                    });
                    var del = createElement('a', td);
                    $(del).addClass('circle-btn').addClass('ml-2');
                    $(del).attr('href', '##');
                    $(del).click(function () {
                        deleteInfo(item['id']);
                    });
                    $(edit).append("<svg><use xlink:href='#icon-bianjiicon'></use></svg>");
                    $(del).append("<svg><use xlink:href='#icon-shanchuicon'></use></svg>");
                    break;
            }
        });

        $("#page").paging({
            pageNo: pageIndex,
            totalPage: payload['pages'],
            totalSize: payload['total'],
            showJump: true,
            callback: function (num) {
                $.cookie("prdEquMaintenanceCookieNum", num, {path: '/'});
                loadMaintenanceListTwo(num);
            },
            // showSizeChange: true,
            // sizeList: [5, 10, 15, 20],
            // pageSize: pageSize,
            // sizeChangeFun: function (size) {
            //     pageSize = size;
            //     loadMaintenanceData(1);
            // }
        });

        $('.more-tooltip').tooltip();
        window.parent.changeIframeH();
        hideLoading();
    })
}

function quickQuerySelector(event) {
    var value = $(event).val();
    var dateObj1 = new Date();
    var dateObj2 = new Date();
    var day = dateObj1.getDate();
    dateObj2.setDate(day - value + 1);
    $('#searchTime').val(getFormatTime(dateObj2).formatDate + ' ~ ' + getFormatTime(dateObj1).formatDate);

}

laydate.render({
    elem: '#searchTime',
    range: '~'
});

laydate.render({
    elem: '#search_month',
    type: 'month'
});

$("#page").paging({
    pageNo: 1,
    totalPage: 0,
    totalSize: 0,
    callback: function (num) {
    }
});

var chart_pie = echarts.init(document.getElementById('chart_pie'));//维保状态
var chart_pie2 = echarts.init(document.getElementById('chart_pie2'));//维保记录

var option_pie = {//维保状态
    color: ['#0096FF', '#5DDF91', '#F8DD83', '#F95959', '#FF7931'],
    legend: {
        top: 'bottom',
        icon: 'rect',
        itemHeight: 16,
        itemWidth: 16,
        itemGap: 16,
        width: 340,
        padding: [0, 0],
        textStyle: {
            color: '#83D0EF',
            fontSize: 16,
            padding: [0, 5]
        }
    },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    series: [{
        name: '设备数量',
        type: 'pie',
        radius: [62, 86],
        center: ['50%', '42%'],
        label: {
            formatter: '{b}:{c}次',
            fontSize: 14
        },
        labelLine: {
            length: 5,
            length2: 10
        },
        data: [
            {value: 0, name: '应维保'},
            {value: 0, name: '已维保'},
            {value: 0, name: '待维保'},
            {value: 0, name: '已延期'},
            {value: 0, name: '延期保养'}
        ]
    }]
};

// 设置显示的行
function set_trTo(e) {
    var start = (e - 1) * 5 + 1;
    var end = e * 5;
    $('#maintenance_List tbody tr').addClass('d-none');
    for (var i = start; i <= end; i++) { // tr_len是要控制的tr个数
        $("#tr_" + i).removeClass('d-none');
    }
}

/* 设置分页，条件：分页组件id：page，表格id：data_table，每页展示10行 */
function set_pagingTo(e, dm) {
    $("#page").paging({
        pageNo: 1,
        totalPage: Math.ceil(e / 5),
        totalSize: e,
        callback: function (num) {
            set_trTo(num);
        }
    });
    set_trTo(1);
    if (e < 1) {
        dm.empty();
        dm.append($("<tr><td align='center' colspan='15'>选择条件内无数据</td></tr>"));
    }
    ;
}

function loadMaintenanceList() {
    showLoading(LOADING);
    var param = $('#param_id').val();
    getJson('/maintenance/list', null, 'GET', function (data) {
        var group1 = [];
        var group2 = [];
        var group3 = [];
        var group4 = [];
        var group5 = [];
        var month = getDate(new Date()).month();
        var date = getDate(new Date()).date();
        var year = getDate(new Date()).year();
        var list = data['payload']['data'];
        var extension = data['payload']['extension'];
        list.map(function (item) {
            if (!item['lastMaintenance']) {
                item['lastMaintenance'] = item['createTime'];
            }
            /*本次维保时间*/
            var toMaintenance = parseInt(item['lastMaintenance']);
            /*维保周期转换为时间戳*/
            var cycle = parseInt(item['cycle']);
            /*应维保时间 本次维保时间加周期*/
            item['maintenanceDate'] = toMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
            item['nextMaintenance'] = toMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
            /*应维保时间  本次维保时间加周期*/
            var maintenanceDate = toMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
            if (getDate(maintenanceDate).year() === year && getDate(maintenanceDate).month() === month) {
                /*应维保*/
                if (getDate(maintenanceDate).date() === date) {
                    group2.push(item);
                } else   /*待维保*/
                if (contrastTime(getDate(maintenanceDate).date(), date)) {
                    group3.push(item);
                }
            }
            /*已延期*/
            if (contrastTime(date, getDate(maintenanceDate).date())) {
                group4.push(item);
            }
            /*已维保*/
            if (getDate(toMaintenance).year() === year && getDate(toMaintenance).month() === month) {
                if (!item['previousMaintenance']) {
                    item['previousMaintenance'] = item['createTime'];
                }
                /*上次维保时间*/
                var previousMaintenance = parseInt(item['previousMaintenance']);
                /*应维保日期*/
                item['maintenanceDate'] = previousMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
                if (getDate(item['maintenanceDate']).year() === year && getDate(item['maintenanceDate']).month() === month) {
                    group1.push(item);
                }
                item['nextMaintenance'] = toMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
            }

        });
        extension.map(function (item) {
            if (!item['lastMaintenance']) {
                item['lastMaintenance'] = item['createTime'];
            }
            /*维保周期转换为时间戳*/
            var cycle = parseInt(item['cycle']);
            var lastMaintenance = parseInt(item['lastMaintenance']);
            item['maintenanceDate'] = lastMaintenance + parseInt(cycle * 24 * 60 * 60 * 1000);
            item['nextMaintenance'] = item['maintenanceDate'] + parseInt(cycle * 24 * 60 * 60 * 1000);
            group5.push(item);
        });
        switch (param) {
            case '1':
                buildData(group1, '已维保', 'build');
                break;
            case '2':
                buildData(group3, '待维保', 'build');
                break;
            case '3':
                buildData(group4, '已延期', 'build');
                break;
            case '4':
                buildData(group2, '应维保', 'build');
                break;
            case '5':
                buildData(group5, '延期保养', 'build');
                break;
            case '0':
                buildData(group4, '已延期', 'build');
                buildData(group2, '应维保', 'append');
                buildData(group1, '已维保', 'append');
                buildData(group3, '待维保', 'append');
                buildData(group5, '延期保养', 'append');
                break;
        }
        if (list.length > 0) {
            $('#wait_List .wsj').remove();
        }
        var count = [
            {name: '应维保', value: group2.length},
            {name: '已维保', value: group1.length},
            {name: '待维保', value: group3.length},
            {name: '已延期', value: group4.length},
            {name: '延期保养', value: group5.length}
        ];
        chart_pie.setOption({
            series: [{
                data: count
            }]
        });
        $('#dydb').text(group1.length + group2.length + group3.length + group4.length);
        hideLoading();
    });
}

function buildData(data, status, method) {
    for (var i = 1; i < data.length; i++) {
        for (var j = 0; j < i; j++) {
            if (data[i]['nextMaintenance'] < data[j]['nextMaintenance']) {
                var temp = data[i];
                data[i] = data[j];
                data[j] = temp;
                temp = null;
            }
        }
    }
    if (method == 'build') {
        buildTable($('#wait_List'), maintenanceTitle, maintenanceLabel, data, function (td, label, item) {
            switch (label) {
                case 'cycle':
                    $(td).text(item[label] + '天');
                    break;
                case 'lastMaintenance':
                    $(td).text(getDate(item[label]).date());
                    break;
                case 'maintenanceDate':
                    $(td).text(getDate(item[label]).date());
                    break;
                case 'nextMaintenance':
                    $(td).text(getDate(item[label]).date());
                    break;
                case 'status':
                    $(td).text(status);
                    break;
            }
        });
    }
    if (method == 'append') {
        // 追加数据
        appendTableData($('#wait_List'), maintenanceLabel, data, function (td, label, item) {
            switch (label) {
                case 'cycle':
                    $(td).text(item[label] + '天');
                    break;
                case 'lastMaintenance':
                    $(td).text(getDate(item[label]).date());
                    break;
                case 'maintenanceDate':
                    $(td).text(getDate(item[label]).date());
                    break;
                case 'nextMaintenance':
                    $(td).text(getDate(item[label]).date());
                    break;
                case 'status':
                    $(td).text(status);
                    if (status == '已延期') {
                        $(td).addClass('text-fault');//已延期标颜色，其他状态不标
                    }
                    break;
            }
        });
    }

}